package service

import (
	"errors"
	"hello/args"
	"hello/model"
	"time"
)

type CommunityService struct {
	Args args.CommunityArg
}

func (s *CommunityService) Create() error {

	tmp := model.Community{
		Name: s.Args.Name,
	}

	_, err := DbEngin.Where("name = ?", s.Args.Name).Cols("id").Get(&tmp)
	if err != nil {
		return err
	}
	if tmp.Id > 0 {
		return errors.New("群名称必须唯一")
	}

	community := model.Community{
		Name:      s.Args.Name,
		OwnerId:   s.Args.UserId,
		Cate:      model.COMMUNITY_CATE_COM,
		CreatedAt: time.Now(),
	}
	_, err = DbEngin.InsertOne(&community)

	if err != nil {
		return err
	}

	err = InsertContactOne(s.Args.UserId, community.Id, model.CONCAT_CATE_COMMUNITY)

	return err
}

func (s *CommunityService) List() ([]model.Community, error)  {

	if s.Args.UserId <= 0 {
		return nil, errors.New("user id未传入")
	}

	concatList := make([]model.Concat, 0)

	err := DbEngin.Where("owner_id = ? and cate = ?", s.Args.UserId, model.CONCAT_CATE_COMMUNITY).Cols("dst_obj").Find(&concatList)
	if err != nil {
		return nil, err
	}
	dstIds := make([]int64, 0)
	for _, concat := range concatList {
		dstIds = append(dstIds, concat.DstObj)
	}

	result := make([]model.Community, 0)
	err = DbEngin.In("id", dstIds).Find(&result)

	return result, err
}

func (s *CommunityService) Join() error  {
	if s.Args.UserId <= 0 || s.Args.Name == ""  {
		return errors.New("参数不对")
	}

	var community  model.Community
	_, err := DbEngin.Where("name = ?", s.Args.Name).Cols("id").Get(&community)
	if err != nil {
		return err
	}
	if community.Id <= 0 {
		return errors.New("此群不存在")
	}

	var tmp model.Concat
	_, err = DbEngin.Where("owner_id = ? and dst_obj = ? and cate = ?", s.Args.UserId,
		community.Id, model.COMMUNITY_CATE_COM).Cols("id").Get(&tmp)
	if err != nil {
		return err
	}
	if tmp.Id > 0 {
		return errors.New("已经加入了")
	}

	err = InsertContactOne(s.Args.UserId, community.Id, model.CONCAT_CATE_COMMUNITY)

	return err
}